package so.ruo.api;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class BaseComment implements Comment {

	private Logger logger = Logger.getLogger(BaseComment.class);

	private CloseableHttpResponse response = null;
	private HttpClientContext context = null;
	private CloseableHttpClient httpclient = null;
	private HttpHost targetHost = null;
	private HttpHost proxyHost = null;
	private CookieStore cookieStore = null;
	private Proxy proxy = null;
	private RequestConfig config = null;
	private Map<String, String> headMap = null;
	private String charset = "utf-8";
	private long contentLength = -1;
	private String returns = null;
	private LaxRedirectStrategy redirectStrategy = null;

	public BaseComment() {
		if (redirectStrategy == null) {
			redirectStrategy = new LaxRedirectStrategy();
		}
		if (httpclient == null) {
			PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
			connManager.setMaxTotal(200);
			connManager.setDefaultMaxPerRoute(20);
			connManager.closeIdleConnections(120, TimeUnit.SECONDS);
			httpclient = HttpClients.custom().setRedirectStrategy(redirectStrategy).setConnectionManager(connManager).build();
		}
		if (cookieStore == null) {
			cookieStore = new BasicCookieStore();
		}
		if (context == null) {
			context = HttpClientContext.create();
			context.setCookieStore(cookieStore);
		}
	}

	@Override
	public String post(String host, String site, Map<String, String> postInfo) throws Exception {

		System.out.println(host);
		System.out.println(site);
		try {
			HttpPost httpPost = new HttpPost(site);
			if (proxy != null) {
				targetHost = new HttpHost(host, 80, "http"); // 设定目标站点
				proxyHost = new HttpHost(proxy.getIp(), proxy.getPort(), proxy.getType().name()); // 设置代理对象 ip/代理名称,端口
				config = RequestConfig.custom().setProxy(proxyHost).build();
				httpPost.setConfig(config);
			}

			// 提交参数列表
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			Iterator<String> iterator = postInfo.keySet().iterator();
			String key = null;
			String value = null;
			while (iterator.hasNext()) {
				key = iterator.next();
				value = postInfo.get(key);
				System.out.println(key + "=++=" + value);
				nvps.add(new BasicNameValuePair(key, value));
			}

			if (headMap != null) {
				iterator = headMap.keySet().iterator();
				while (iterator.hasNext()) {
					key = iterator.next();
					value = headMap.get(key);
					System.out.println(key + "==" + value);
					httpPost.setHeader(key, value);
				}
			}

			UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nvps, charset);
			httpPost.setEntity(urlEncodedFormEntity);

			if (proxy != null) {
				response = httpclient.execute(targetHost, httpPost, context);
			} else {
				response = httpclient.execute(httpPost, context);
			}

			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				// 获取响应实体
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					contentLength = entity.getContentLength();// 响应内容长度
					returns = EntityUtils.toString(entity, charset);// 响应内容
					EntityUtils.consume(entity);
				}
			} else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_MOVED_PERMANENTLY) {
				// 当前页面发生重定向了
				Header[] headers = response.getHeaders("Location");
				if (headers != null && headers.length > 0) {
					String redirectUrl = headers[0].getValue();
					logger.debug("重定向的URL:" + redirectUrl);
					redirectUrl = redirectUrl.replace(" ", "%20");
					Thread.sleep(3000);
					HttpGet httpget = new HttpGet(redirectUrl);
					response = httpclient.execute(httpget, context);
					EntityUtils.consume(response.getEntity());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			response.close();
		}
		return returns;
	}

	public CloseableHttpResponse getResponse() {
		return response;
	}

	public void setResponse(CloseableHttpResponse response) {
		this.response = response;
	}

	public HttpClientContext getContext() {
		return context;
	}

	public void setContext(HttpClientContext context) {
		this.context = context;
	}

	public CloseableHttpClient getHttpclient() {
		return httpclient;
	}

	public void setHttpclient(CloseableHttpClient httpclient) {
		this.httpclient = httpclient;
	}

	public HttpHost getTargetHost() {
		return targetHost;
	}

	public void setTargetHost(HttpHost targetHost) {
		this.targetHost = targetHost;
	}

	public HttpHost getProxyHost() {
		return proxyHost;
	}

	public void setProxyHost(HttpHost proxyHost) {
		this.proxyHost = proxyHost;
	}

	public CookieStore getCookieStore() {
		return cookieStore;
	}

	public void setCookieStore(CookieStore cookieStore) {
		this.cookieStore = cookieStore;
	}

	public Proxy getProxy() {
		return proxy;
	}

	public void setProxy(Proxy proxy) {
		this.proxy = proxy;
	}

	public Map<String, String> getHeadMap() {
		return headMap;
	}

	public void setHeadMap(Map<String, String> headMap) {
		this.headMap = headMap;
	}

	public RequestConfig getConfig() {
		return config;
	}

	public void setConfig(RequestConfig config) {
		this.config = config;
	}

	public String getCharset() {
		return charset;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}

	public long getContentLength() {
		return contentLength;
	}

	public void setContentLength(long contentLength) {
		this.contentLength = contentLength;
	}

	public String getReturns() {
		return returns;
	}

	public void setReturns(String returns) {
		this.returns = returns;
	}

	public LaxRedirectStrategy getRedirectStrategy() {
		return redirectStrategy;
	}

	public void setRedirectStrategy(LaxRedirectStrategy redirectStrategy) {
		this.redirectStrategy = redirectStrategy;
	}

}
